from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from google.appengine.ext import db

import store
import answer
from Message import Message

class Wave(db.Model):
	id = db.StringProperty()
	active = db.BooleanProperty()

def OnRobotAdded(properties, context):
	"""Invoked when the robot has been added."""
	root_wavelet = context.GetRootWavelet()
	wave = Wave()
	wave.active = False
	wave.id = root_wavelet.GetWaveId()
	wave.put()



def OnBlibCreated(properties, context):
	blipId = properties['blipId'];
	blip = context.GetBlipById(blipId)
	text = blip.GetDocument().GetText().lower()
	if blip.GetCreator() != 'tooangel-wave@appspot.com':
		# Save the message
		message = store.message(text)

		# Save the conversation
		if not blip.IsRoot():
			parentText = context.GetBlipById(blip.GetParentBlipId()).GetDocument().GetText().lower()
			store.conversation(parentText, message)
	
		# Get an answer	
		answer.message(message, blip)
	else:
#		valueUpdate(blip, context)
		pass

def valueUpdate(blip, context):
	direction = None
	element = None
	for key, elem in blip.GetElements().iteritems():
		if(elem.type == document.ELEMENT_TYPE.GADGET and hasattr(elem,'dir')):
			direction = elem.dir
			element = elem
			break

	if direction:
		new_blip = context.GetRootWavelet().CreateBlip()
		new_blip.GetDocument().SetText('SUM: %s' % direction) 
		if not direction == None:
			text = blip.GetDocument().GetText().lower()
			query = Message.gql("WHERE text = :1", text)
			message = query.get()
			if message:
				if direction == '+':
					message.value += 1;
				elif direction == '-':
					message.value -= 1;
				message.put()
				elem.diff = message.value;
				new_blip = context.GetRootWavelet().CreateBlip()
				new_blip.GetDocument().SetText('SUM: %s ' % directon) 

def OnBlibChange(properties, context): 
	blipId = properties['blipId'];
	blip = context.GetBlipById(blipId)
	#text = blip.GetDocument().GetText()
#	element = blip.GetDocument().GetElement(0)
#	elements = blip.getElements()
	response = ""
#	childern = blip.getChildren()
#	for child in children:
#		response = child.GetDocument().GetText()
			
#	newBlip = blip.CreateChild()
##	newBlip.GetDocument().SetText("blipId: " + blipId + " elements: " + response + " properties: " + str(properties) + " context: " + str(context))
#		newBlip.GetDocument().SetText("bla: " + text)
		
	#	newBlip = blip.CreateChild()
	#	newBlip.GetDocument().SetText(response)
	#	gadget = document.Gadget('http://www.elizabethsgadgets.appspot.com/public/gadget.xml')
	#	newBlip.GetDocument().AppendElement(gadget)
#	else:
#    newBlip = blip.CreateChild()
#    newBlip.GetDocument().SetText(blip.GetDocument().GetText())
  

#def Notify(context):
#  root_wavelet = context.GetRootWavelet()
#  root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody!")

if __name__ == '__main__':
  myRobot = robot.Robot('TooAngel Wave', 
      image_url='http://tooangel-wave.appspot.com/public/icon.png',
      version='0.32',
      profile_url='http://tooangel-wave.appspot.com/')
#  myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
#  myRobot.RegisterHandler(events.WAVELET_BLIP_CREATED, OnBlibCreated)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlibCreated)
  myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnBlibChange)
  myRobot.Run()
